package com.google.code.virtualhockey.vhx.shared.rpc;

import com.google.code.virtualhockey.vhx.shared.error.WebNotAuthenticatedException;
import com.google.code.virtualhockey.vhx.shared.error.WebNotAuthorisedException;
import com.google.code.virtualhockey.vhx.shared.error.WebServerException;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Base class for all specific command callback implementations. Can be used
 * everywhere where a GWT {@link com.google.gwt.user.client.rpc.AsyncCallback} is expected.
 *
 * @param <T> the type of response that is expected to be received
 */
public abstract class AbstractCommandCallback<T extends IResponse> implements AsyncCallback<T>
{
  /**
   * @see com.google.gwt.user.client.rpc.AsyncCallback#onFailure(Throwable)
   */
  public void onFailure( Throwable t )
  {
    if ( t instanceof WebNotAuthenticatedException )
    {
      // redirect to the login page
      //
      Window.open( ( (WebNotAuthenticatedException) t ).getLoginRedirectUrl(), "_self", null );
    }
    else if ( t instanceof WebNotAuthorisedException )
    {
      WebNotAuthorisedException ex = (WebNotAuthorisedException) t;
      String strRedirectUrl = ex.getErrorRedirectUrl();

      // display an error message if we have no specific error page URL or use that URL
      //
      if ( strRedirectUrl == null )
        Window.alert( ex.getMessage() );
      else
        Window.open( strRedirectUrl, "_self", null );
    }
    else if ( t instanceof WebServerException )
      Window.alert( "WebServerException: " + t.getMessage() );
    else
      Window.alert( "Unexpected GWT/RPC exception: " + t.getClass().getName() + "\n" + t.toString() );
  }

  /**
   * @see com.google.gwt.user.client.rpc.AsyncCallback#onSuccess(Object)
   */
  public void onSuccess( T response )
  {
    // redirect to handleAnswer() method
    //
    handleAnswer( response );
  }

  /**
   * Is called once a response has been received. This should be overridden in order to do
   * something with the obtained result.
   *
   * @param response the received command response
   */
  public abstract void handleAnswer( T response );
}
